package com.moyq5.wifi.joystick;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.graphics.Bitmap;
import android.net.wifi.p2p.WifiP2pManager;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ScrollView;
import android.widget.TextView;

import androidx.appcompat.app.AppCompatActivity;

import java.text.SimpleDateFormat;
import java.util.Date;

import static android.view.ViewGroup.LayoutParams.MATCH_PARENT;
import static android.view.ViewGroup.LayoutParams.WRAP_CONTENT;
import static android.widget.LinearLayout.HORIZONTAL;
import static com.moyq5.wifi.joystick.Console.DEBUG;
import static com.moyq5.wifi.joystick.Console.ERROR;
import static com.moyq5.wifi.joystick.Console.INFO;
import static com.moyq5.wifi.joystick.Console.PARAM_LEVEL;
import static com.moyq5.wifi.joystick.Console.PARAM_MESSAGE;
import static com.moyq5.wifi.joystick.Console.WARN;

public abstract class ConsoleActivityAbstract extends AppCompatActivity {
    private static final Console console = ConsoleFactory.get(ConsoleActivityAbstract.class);
    private ScrollView scrollView;
    private LinearLayout consoleView;
    private int colorWarn;
    private int colorDanger;
    private int colorInfo;

    private final BroadcastReceiver consoleReceiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            int level = intent.getIntExtra(PARAM_LEVEL, INFO);
            String message = intent.getStringExtra(PARAM_MESSAGE);
            switch (level) {
                case DEBUG:
                case INFO:
                    info(message);
                    break;
                case WARN:
                    warn(message);
                    break;
                case ERROR:
                    error(message);
                    break;
            }

        }
    };


    protected WifiP2pManager manager;
    protected WifiP2pManager.Channel channel;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(layoutId());
        scrollView = findViewById(R.id.scroll);
        consoleView = findViewById(R.id.console);
        consoleView.addOnLayoutChangeListener((v, left, top, right, bottom, oldLeft, oldTop, oldRight, oldBottom) -> {
            scrollView.fullScroll(ScrollView.FOCUS_DOWN);
        });
        colorInfo = getColor(R.color.colorBlack);
        colorWarn = getColor(R.color.colorWarning);
        colorDanger = getColor(R.color.colorDanger);


        manager = (WifiP2pManager) getSystemService(Context.WIFI_P2P_SERVICE);
        channel = manager.initialize(this, getMainLooper(), () -> error("p2p 通道连接已断开"));


    }

    abstract int layoutId();

    @Override
    protected void onResume() {
        super.onResume();
        App.localRegister(this, consoleReceiver, new IntentFilter(Console.class.getName()));
    }

    @Override
    protected void onPause() {
        super.onPause();
        App.localUnregister(this, consoleReceiver);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();

    }

    private void info(String format, Object... args) {
        console(colorInfo, format, args);
    }

    private void warn(String format, Object... args) {
        console(colorWarn, format, args);
    }

    private void error(String format, Object... args) {
        console(colorDanger, format, args);
    }

    private void replace(String format, Object... args) {
        int count = consoleView.getChildCount();
        if (count == 0) {
            info(format, args);
            return;
        }
        View child = consoleView.getChildAt(count - 1);
        if (child instanceof TextView) {
            ((TextView)child).setText(String.format(format, args));
        } else {
            info(format, args);
        }
    }

    private void bitmap(Bitmap bitmap) {
        try {
            ImageView imageView = new ImageView(this);
            imageView.setLayoutParams(new LinearLayout.LayoutParams(MATCH_PARENT, 150));
            imageView.setImageBitmap(bitmap);
            addView(imageView);
        } catch (Throwable e) {
            Log.e("TAG", "bitmap: ", e);
        }
    }

    private void console(int color, String format, Object... args) {
        String message = String.format(format, args);
        try {
            LinearLayout layout = new LinearLayout(this);
            layout.setLayoutParams(new LinearLayout.LayoutParams(MATCH_PARENT, WRAP_CONTENT));
            layout.setOrientation(HORIZONTAL);

            TextView timeView = new TextView(this);
            timeView.setLayoutParams(new LinearLayout.LayoutParams(WRAP_CONTENT, WRAP_CONTENT));
            timeView.setText(new SimpleDateFormat("HH:mm:ss").format(new Date()) + " ");
            timeView.setTextColor(color);
            layout.addView(timeView);

            TextView textView = new TextView(this);
            textView.setLayoutParams(new LinearLayout.LayoutParams(MATCH_PARENT, WRAP_CONTENT));
            textView.setText(message);
            textView.setTextColor(color);
            layout.addView(textView);

            addView(layout);
        } catch (Throwable e) {
            Log.e("TAG", "console: ", e);
        }
    }

    private void addView(View child) {
        if (consoleView.getChildCount() > 500) {
            consoleView.removeViewAt(0);
        }
        consoleView.addView(child);
    }

}